import { defineStore } from 'pinia'
import { ref, computed } from 'vue'

export const useTabsStore = defineStore('tabs', () => {
  const tabs = ref([
    {
      path: '/dashboard',
      name: 'Dashboard',
      title: '仪表盘',
      closable: false // 仪表盘默认不可关闭
    }
  ])
  
  const activeTab = ref('/dashboard')

  // 添加标签页
  const addTab = (route) => {
    const existingTab = tabs.value.find(tab => tab.path === route.path)
    
    if (!existingTab) {
      tabs.value.push({
        path: route.path,
        name: route.name,
        title: getTabTitle(route.path),
        closable: true
      })
    }
    
    activeTab.value = route.path
  }

  // 关闭标签页
  const removeTab = (targetPath) => {
    const targetIndex = tabs.value.findIndex(tab => tab.path === targetPath)
    
    if (targetIndex === -1) return
    
    // 如果关闭的是当前活跃标签页
    if (activeTab.value === targetPath) {
      // 切换到相邻的标签页
      if (tabs.value.length > 1) {
        if (targetIndex > 0) {
          activeTab.value = tabs.value[targetIndex - 1].path
        } else {
          activeTab.value = tabs.value[targetIndex + 1].path
        }
      }
    }
    
    tabs.value.splice(targetIndex, 1)
    
    // 如果关闭后没有标签页了，默认回到仪表盘
    if (tabs.value.length === 0) {
      addTab({ path: '/dashboard', name: 'Dashboard' })
    }
  }

  // 设置活跃标签页
  const setActiveTab = (path) => {
    activeTab.value = path
  }

  // 关闭所有标签页（除了仪表盘）
  const closeAllTabs = () => {
    tabs.value = tabs.value.filter(tab => !tab.closable)
    activeTab.value = '/dashboard'
  }

  // 关闭其他标签页
  const closeOtherTabs = (keepPath) => {
    tabs.value = tabs.value.filter(tab => !tab.closable || tab.path === keepPath)
    activeTab.value = keepPath
  }

  // 获取标签页标题
  const getTabTitle = (path) => {
    const titleMap = {
      '/dashboard': '仪表盘',
      '/users': '用户管理',
      '/products': '商品管理',
      '/orders': '订单管理',
      '/settings': '系统设置',
      '/buttons-demo': '按钮演示',
      '/express-stage': '驿站配置',
      '/package-config': '包裹配置'
    }
    return titleMap[path] || '未知页面'
  }

  return {
    tabs,
    activeTab,
    addTab,
    removeTab,
    setActiveTab,
    closeAllTabs,
    closeOtherTabs
  }
}) 